package team.bluepen.supermarket.data.entity;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import team.bluepen.supermarket.kafka.KafkaDeserializer;
import team.bluepen.supermarket.kafka.KafkaSerializer;

import java.beans.ConstructorProperties;
import java.io.Serializable;
import java.util.Objects;

/**
 * @author RollW
 */
public class ProductStatusAmount implements Serializable {
    @JsonProperty("state")
    private final boolean state;

    @JsonProperty("amount")
    private final long amount;

    @ConstructorProperties({"state", "amount"})
    public ProductStatusAmount(boolean state, long amount) {
        this.state = state;
        this.amount = amount;
    }

    public boolean isState() {
        return state;
    }

    public long getAmount() {
        return amount;
    }



    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ProductStatusAmount that = (ProductStatusAmount) o;
        return state == that.state && amount == that.amount;
    }

    @Override
    public int hashCode() {
        return Objects.hash(state, amount);
    }

    public static KafkaSerializer<ProductStatusAmount> serializer() {
        return Serial.INSTANCE;
    }

    public static KafkaDeserializer<ProductStatusAmount> deserializer() {
        return Serial.INSTANCE;
    }

    private static class Serial implements KafkaSerializer<ProductStatusAmount>,
            KafkaDeserializer<ProductStatusAmount> {
        private final ObjectMapper objectMapper = new ObjectMapper();

        @Override
        public String serialize(ProductStatusAmount productStatusAmount) {
            try {
                return objectMapper.writeValueAsString(productStatusAmount);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public ProductStatusAmount deserialize(String data) {
            try {
                return objectMapper.readValue(data, ProductStatusAmount.class);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }

        static final Serial INSTANCE = new Serial();
    }
}
